import fs from 'fs';
import { tools } from './tools/tools';

export namespace assets_cleaner {
    export class AssetsCleaner {
        constructor(root: string, resName: string) {
            if (!resName) {
                console.warn('empty resname, type --ext <resname>');
                return;
            }
            this.curRoot = root;
            let config = tools.GenricCfg();

            let cfgFile = fs.readFileSync(`${this.curRoot}/${config.cfg_path}/${config.cfg_file}`, { encoding: 'utf-8' });
            let dataPac = JSON.parse(cfgFile || '{}') as tools.GENRATOR_CFG_TYPE[];
            for (let cfgPac of dataPac) {
                if (!!cfgPac && resName == cfgPac.name) {
                    this.DeleteFile(cfgPac.exclude);
                }
            }
        }

        private async DeleteFile(globFiles: string[]): Promise<void> {
            let config = tools.QueryEgretProperties(this.curRoot);

            let files = await tools.GlobFiles(globFiles, config?.assets_clean?.delete_file_exc || [], `${config?.path || tools.DEF_RES_PATH}`, { cwd: this.curRoot });
            let path: string;
            let delDic: string[] = [];
            for (let file of files) {
                path = `${this.curRoot}/${file}`;
                if (fs.existsSync(path)) {
                    if (fs.statSync(path).isDirectory()) {
                        fs.rmdirSync(path, { recursive: true });
                    } else {
                        fs.rmSync(path);
                    }
                    delDic.push(file);
                }
            }
            // fs.rmSync(``)
            let curTime = new Date();
            let reportPath = `${this.curRoot}/delResReport ${curTime.getFullYear()}-${curTime.getMonth()}-${curTime.getDay()}-${curTime.getHours()}-${curTime.getMinutes()}-${curTime.getSeconds()}.json`;
            let fscontext = fs.openSync(reportPath, 'w');
            fs.writeFileSync(reportPath, JSON.stringify(delDic, null, 4), { encoding: 'utf8' });
            fs.closeSync(fscontext);

            console.log(`gen delete report to ${reportPath}`);
        }

        private curRoot!: string;
    }

}